package com.swu.pad.system.service.impl;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swu.pad.system.dao.UserDao;
import com.swu.pad.system.entity.User;
import com.swu.pad.system.service.UserService;
import com.swu.pad.util.StringUtil;
import com.swu.pad.util.EPLiteClient.EPLiteClient;

@Service
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;
	@Autowired
	private EntityManager entityManager;
	@Autowired
	private EPLiteClient epliteClient;

	public User saveUser(User user) {
		if (!StringUtil.isValid(user.getId())) {
			String authorId = epliteClient.createAuthorIfNotExistsFor(user.getUsername()).get("authorID").toString();
			user.setId(authorId);
		}
		return userDao.save(user);
	}

	public User findUserById(String id) {
		return userDao.findUserById(id);
	}

	public User login(String username, String password) {
		User user = userDao.findUserByUsernameAndPassword(username, password);
		entityManager.clear();// 使对象变成游离状态，不再自动更新
		if (user != null)
			user.setPassword("");
		return user;
	}

}
